import React from "react";
import { Group3D, Line2, LineSegments, LineSegments2, Text2D, Text3D, TextAlign, THREEComponent } from "xsh-react-three";
import Line, { LinePoints } from "xsh-react-three/lib/Line/Line";
import { Vector3 } from "xsh-react-three/lib/Object3D/type";


export type Line3DData = {
    value: number;
    [key: string]: any
}

interface Line3DProps {
    datas?: Line3DData[]
    colors?: string[]
    width?: number;
    height?: number;

    position?: Vector3;
    rotation?: Vector3;
    scale?: Vector3;
}

interface State { }

export default class Line3D extends THREEComponent<Line3DProps, State> {
    constructor(props: Line3DProps) {
        super(props);
    }

    static defaultProps = {
        datas: [],
        colors: ["#f00", "#0f0"],
        width: 10,
        height: 10
    }

    getPoints() {
        const { datas = [], width = 10, height = 10 } = this.props;

        let points: LinePoints = [];

        let length = Math.max(1, datas.length);

        let maxValue = Math.max(...datas.map(d => d.value));

        let currenIndex = 0;

        for (let i = 0; i <= 100; i++) {

            if (datas[i]) {
                currenIndex = i;
                points.push([currenIndex * (width / length), datas[currenIndex].value * (height / maxValue), 0]);
            } else {
                points.push([(currenIndex + 1) * (width / length), 0, 0]);
            }

        }

        return points;
    }

    render() {
        const {
            colors = [],
            datas = [],

            position,
            rotation,
            scale,

        } = this.props;
        const points = this.getPoints();
        return (
            <Group3D
                position={position}
                rotation={rotation}
                scale={scale}
            >

                <Line2
                    points={this.getPoints()}
                    color={colors}
                    linewidth={2}
                />

                {
                    points.slice(0, datas.length).map((p, index) => {
                        return (
                            <Text2D
                                key={index}
                                size={1}
                                color={colors[index]}
                                text={String(p[1].toFixed(1))}
                                scale={{ x: 0.5, y: 0.5 }}
                                position={{ x: p[0], y: p[1], z: 0.1 }}
                                textAlign={TextAlign.CENTER_BOTTOM}
                            />
                        );
                    })

                }

            </Group3D>
        );
    }
}